/*
 * @Descripttion: 
 * @version: 
 * @Author: lily
 * @Date: 2021-05-07 11:16:13
 * @LastEditors: lily
 * @LastEditTime: 2021-05-07 14:33:39
 */
/*
 * @lc app=leetcode.cn id=665 lang=javascript
 *
 * [665] 非递减数列
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {boolean}
 */

//  思想：
//  https://leetcode-cn.com/problems/non-decreasing-array/solution/3-zhang-dong-tu-bang-zhu-ni-li-jie-zhe-d-06gi/

//  复杂度：O(n) O(1)

var checkPossibility = function (nums) {
    const len = nums.length
    let flag = 0
    for (let i = 1; i < len; i++) {
        if (nums[i - 1] > nums[i]) {
            // 保证修改的数要使得数组不递减
            if (i === 1 || nums[i] >= nums[i - 2]) {
                // 修改前一个数
                nums[i - 1] = nums[i]
            } else {
                // 修改当前数
                nums[i] = nums[i - 1]
            }
            flag++
        }
    }
    return flag <= 1
};
// @lc code=end


console.log(checkPossibility([3, 4, 2, 3]));
